var vehicle = {
	init : function () {	
		this.queryW();
		this.loadVehicle();
		this.bindShareVehicle();
		this.bind();
	},
	
	/**
	 * 获取个dom宽度高度
	 */
	queryW : function(){
		var winW = $('body').width();
		$('.querys').width(winW - 210);
		$('.tab-alarm').height(nav.whiceH[0] - 43);
		//$('#treeId').height(nav.whiceH[0] - 46);
	},
	loadVehicle:function(){
		$("#vehicleTable").flexigrid({
			url : appCtx + "system/vehicle/loadVehicle.html",
			dataType : 'json',
			colModel : this.getColumn(),
			resizable : false,
			sortname : "vehicleId",// 第一次加载数据时排序列
			sortorder : "desc",// 第一次加载数据时排序类型
			usepager : true,// 是否分页，默认为true。
			showToggleBtn : false,
			page : 10,
			showTableToggleBtn : true,// 是否显示收起/打开按钮,默认不显示。
			useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
			rp : 10,// 每页记录数，默认为10
			checkbox : true,// 是否要多选框,默认为false。
			rowId : 'vehicleId',// 多选框绑定行的id,只有checkbox : true时才有效。
			singleSelect : true,
			height : nav.whiceH[1] - 140, // 表格高度
			titDisplay : false,
			
		// 表格高度
		});
	},
	getColumn:function(){
		return [{
			display : '操作',
			name : '',
			width : 250,
			sortable : true,
			align : 'center',
			paramcolnames:['vehicleId'],
	        handlefunction:vehicle.operationStr			
		},{
			display : 'vehicleId',
			name : 'vehicleId',
			width : 0,
			sortable : false,
		    hide:true,
			align : 'left',
		},{
			display : '分享状态',
			name : 'shareState',
			width : 65,
			sortable : true,
			align : 'center',
			paramcolnames:['shareKey'],
	        handlefunction:vehicle.shareKeyStr
		},{
			display : '车牌号码',
			name : 'registrationNO',
			width : 100,
			sortable : true,
			align : 'center'
		},{
			display : '企业名称',
			name : 'unitName',
			width : 200,
			sortable : true,
			align : 'center'
		},{
			display : '自编号',
			name : 'internalNumber',
			width : 100,
			sortable : true,
			align : 'center'
		},{
			display : '通信号',
			name : 'commNo',
			width : 100,
			sortable : true,
			align : 'center'
		},{
			display : 'Sim卡号',
			name : 'simNo',
			width : 100,
			sortable : true,
			align : 'center'
		},{
			display : '司机名称',
			name : 'driverName',
			width : 100,
			sortable : true,
			align : 'center'
		},{
			display : '司机联系电话',
			name : 'phone',
			width : 100,
			sortable : true,
			align : 'center'
		},{
			display : '安装日期',
			name : 'setupDateTime',
			width : 100,
			sortable : true,
			align : 'center'
		},{
			display : '备注',
			name : 'remark',
			width : 200,
			sortable : true,
			align : 'center'
		}];
	},
	shareKeyStr:function(shareKey){	
		var base = new Base64();
		var shareTime = base.decode(shareKey);
		var now = new Date().getTime();
		var str = "";
		console.log(shareKey);
		if(shareKey!= "undefined"){
			if(shareTime<now){   //已过期
				str = "<span>已过期</span>";
			}else{               //分享中
				str =  "<span>分享中</span>";
			}
		}else{
			str= "<span>未分享</span>";    //未分享
		}
		return str;
    },
	 /**普通查询*/
    searchTable : function(){
    	var vehicleNo =$.trim($('#vehicleNo').val())
        var internalNumber = $.trim($('#internalNumber').val());
        var paramsGrid = [{
            name : 'vehicleNo',
            value : vehicleNo
        },{
            name : 'internalNumber',
            value : internalNumber
        }];
        $("#vehicleTable").flexOptions({
    		url : appCtx + "system/vehicle/loadVehicle.html",
    		newp : 1,// 设置起始页
    		params : paramsGrid
    	}).flexReload();// 重新加载  
    },
	bindShareVehicle:function(){
		var _this=this;
    	$("#shareVehicleBtn").click(function(){
    		_this.shareVehicle();
    	});  
    	$("#saveVehicleShareDateBtn").click(function(){
    		var value = $("#saveVehicleShareDateBtn").text();
    		if(value == "生成链接" || value =="确定"){
    			_this.saveVehicleShareDate();
    		}else if(value == "复制链接"){
    			_this.copyVehicleShareUrl();
    		}
    	}); 
    	$("#stopVehicleShareDateBtn").click(function(){
    		_this.saveVehicleShareDateForStop();
    	}); 
    	$("#searchUser").click(function(){
    		_this.searchTable();
    	}); 
    	$("#copyVehicleUrlBtn").click(function(){
    		var value = $("#vehicleShareurl_text").text();
    		if(value){
    			_this.copy();
    		}else{
    			 global.ajaxLoading.pop("无分享的链接复制！",true,1000);
    		}
    	}); 
    	
	},
	copy : function(){
		var c1 = new ClipBoard({
		    handlerID: 'copyVehicleUrlBtn',
		    textID: 'vehicleShareurl_text',
		    isAttr: false,
		    type:'copy'
		});
		c1.attach(); // 触发复制/剪切功能
	},
	copyVehicleShareUrl : function(){
		var value = $("#saveVehicleShareDateBtn").text();
		if(value=="复制链接"){
			var c1 = new ClipBoard({
			    handlerID: 'saveVehicleShareDateBtn',
			    textID: 'vehicleShareurl_text',
			    isAttr: false,
			    type:'copy'
			});
			c1.attach(); // 触发复制/剪切功能
		}
	},
	/**
	 * 分享车辆
	 */
	shareVehicle:function(){
		var param=[];
		$('.trSelected td:nth-child(2)').each(function (i) {
            param[i]=$(this).text();
		 });
		 if(param.length==0){
			 global.ajaxLoading.pop("请选择要分享的车辆！",true,1000);
			 return;
		 }
		 $.ajax({
	    	type : 'post',
	    	async : false,
	    	url : appCtx + "system/vehicle/shareVehicle.html?ids="+param,
	    	cache : false,
	    	dataType : "JSON",
	    	success : function(data) {			
	    		if(data){
//	    			console.log(data);
	    			for(var i=0;i<data.length;i++){
	    				var url=appCtx +data[i].url;
	    				window.open(url,'shareWindow' +i);
	    			}
	    		}
	    	}	
	    });	  
	},
	/**
	 * 分享车辆
	 */
	showVehicleShare:function(vehicleId){
		$("#overTime").css("display","none");
		$("#shareVehicleId").val(vehicleId);
		$("#vehicleShareurl_text").text("");
		$("#myModalLabel").text("分享车辆");
		$("#action").val("share");
		$("#shareLink").css("display","block");
		$("#shareTime").css("display","block");		
		$("#vehicleShareModal").modal("show");		
		$("#saveVehicleShareDateBtn").text("生成链接");
		$("#copyVehicleUrlBtn").css("display","block");
	},
	/**
	 * 操作字段
	 */
	operationStr:function(vehicleId){		
		var str = '<a class="shareVehicle" href="javascript:vehicle.showVehicleShare('+vehicleId+')" style="color:blue;">分享车辆</a>'+
		    '&nbsp;&nbsp;<a class="shareVehicle" href="javascript:vehicle.overTimeUpdate('+vehicleId+')" style="color:blue;">过期修改</a>'+
		    '&nbsp;&nbsp;<a class="shareVehicle" href="javascript:vehicle.queryVehicleShare('+vehicleId+')" style="color:blue;">查看分享</a>'+
			'&nbsp;&nbsp;<a class="shareVehicle" href="javascript:vehicle.stopVehicleShare('+vehicleId+')" style="color:blue;">停止分享</a>';
		return str;
    },
    /**
     * 停止分享
     * @param vehicleId
     */
    stopVehicleShare : function(vehicleId){
    	$("#shareVehicleId").val(vehicleId);
    	$("#action").val("stop");
    	$("#tipVehicle").modal("show");
    },
    /**
     * 过期修改
     * @param vehicleId
     */
    overTimeUpdate : function(vehicleId){
    	$("#overTime").css("display","none");
    	$("#shareVehicleId").val(vehicleId);
    	$("#shareTime").css("display","block");
		$("#myModalLabel").text("过期修改");
		$("#action").val("update");
		$("#shareLink").css("display","none");
		$("#vehicleShareModal").modal("show");
		$("#saveVehicleShareDateBtn").text("确定");
    },
    /**
     * 查看分享
     */
    queryVehicleShare : function(vehicleId){
    	$("#vehicleShareurl_overtime").text("");
    	$("#overTime").css("display","block");
    	$("#shareVehicleId").val(vehicleId);
    	$("#vehicleShareurl_text").val("");
		$("#myModalLabel").text("查看分享");
		$("#action").val("show");
		$("#shareLink").css("display","block");
		$("#shareTime").css("display","none");
		$("#vehicleShareModal").modal("show");
		$("#saveVehicleShareDateBtn").text("复制链接");
		$("#copyVehicleUrlBtn").css("display","none");
		$.ajax({
	    	type : 'post',
	    	async : false,
	    	url : appCtx + "system/vehicle/queryVehicleShare.html?vehicleId="+vehicleId,
	    	cache : false,
	    	dataType : "JSON",
	    	success : function(data) {			
	    		if(data){
	    			if(data.msg=="成功"){
	    				if(data.flag=="0"){
	    					$("#vehicleShareurl_text").text(data.vehicleIdStr);
	    					$("#vehicleShareurl_overtime").text(new Date(parseInt(data.overtime)).toLocaleString());
	    				}else{
	    					$("#vehicleShareurl_text").text(data.vehicleIdStr);
	    				}			
	    			}
	    		}
	    	}	
	    });	  
    },
    saveVehicleShareDateForStop:function(){
    	var base = new Base64();
    	var inputDate="2000/01/01 00:00:00";
    	var action = $("#action").val();
    	var decodeKey = new Date(inputDate).getTime();
    	var encodeKey = base.encode(decodeKey.toString());
    	var vehicleId=$("#shareVehicleId").val();
    	$.ajax({
	    	type : 'post',
	    	async : false,
	    	url : appCtx + "system/vehicle/saveVehicleShareDate.html?vehicleId="+vehicleId+"&shareKey="+encodeKey+"&path="+appCtx+"&action="+action,
	    	cache : false,
	    	dataType : "JSON",
	    	success : function(data) {			
	    		if(data){
	    			if(data.msg!="成功"){
	    				global.ajaxLoading.pop(data.msg,true,1000);
	    				$("#tipVehicle").modal('hide');
	    				vehicle.searchTable();
	    			}else{
	    				global.ajaxLoading.pop("操作成功！",true,1000);
		    			var url=appCtx+"system/vehicle/shareVehicle.html?vehicleId="+vehicleId+"&shareKey="+encodeKey;
		    			$("#vehicleShareurl_text").html(url);
			    		$("#vehicleShareurl_text").show();
			    		$("#tipVehicle").modal('hide');
			    		vehicle.searchTable();
	    			}	    			
	    		}  		
	    	}	
	    });	  
    },
    
    saveVehicleShareDate:function(){
    	var base = new Base64();
    	var inputDate=$("#inputDate").val().replace(/\-/g,"\/");
    	var action = $("#action").val();
    	var decodeKey = new Date(inputDate).getTime();
    	var encodeKey = base.encode(decodeKey.toString());
    	if(inputDate==""){
    		global.ajaxLoading.pop("请设置期限！",true,1000);
    		return ;
    	}
    	var now = new Date().getTime();
    	if(decodeKey<now&&action=="share"){
    		global.ajaxLoading.pop("期限不能小于当前时间！",true,1000);
    		return ;
    	}
    	if(decodeKey<now&&action=="update"){
    		global.ajaxLoading.pop("期限不能小于当前时间！",true,1000);
    		return ;
    	}
    	var vehicleId=$("#shareVehicleId").val();
    	$.ajax({
	    	type : 'post',
	    	async : false,
	    	url : appCtx + "system/vehicle/saveVehicleShareDate.html?vehicleId="+vehicleId+"&shareKey="+encodeKey+"&path="+appCtx+"&action="+action,
	    	cache : false,
	    	dataType : "JSON",
	    	success : function(data) {			
	    		if(data){
	    			if(data.msg!="成功"){
	    				global.ajaxLoading.pop(data.msg,true,1000);
	    				var val = $("#saveVehicleShareDateBtn").val();
	    				if(val=="确定"){
	    					$("#vehicleShareModal").modal('hide');
	    				} 
	    				vehicle.searchTable();
//	    				if(action=="share") $("#saveVehicleShareDateBtn").text("复制链接");
	    			}else{
	    				global.ajaxLoading.pop("操作成功！",true,1000);
		    			var url=appCtx+"system/vehicle/shareVehicle.html?shareKey="+encodeKey+"&vehicleId="+vehicleId;
		    			$("#vehicleShareurl_text").html(url);
			    		$("#vehicleShareurl_text").show();
			    		var val = $("#saveVehicleShareDateBtn").text();
	    				if(val=="确定"){
	    					$("#vehicleShareModal").modal('hide');
	    				} 
	    				if(action=="share") $("#copyVehicleUrlBtn").css("display","block");
	    				vehicle.searchTable();
//	    				if(action=="share") $("#saveVehicleShareDateBtn").text("复制链接");
	    			}	    			
	    		}  		
	    	}	
	    });	  
    },
    bind:function(){
    	var _this=this;
    	$("#updateVehiclebtn").click(function(){
    		_this.updVehicle();
    	});
    	$("#updateVehicleInfo").click(function(){
    		_this.updateVehicleInfo();
    	});
    	$("#exportVehicleBtn").click(function(){
    		_this.exportVehicleInfo();
    	});   	
    },
    updVehicle:function(){
    	var checks = $("#vehicleTable").getCheckedRows();
    	if(checks.length>1){
    		global.ajaxLoading.pop("只能选择一条数据操作！",true,1000);
    		return;
    	}
    	if(checks.length==0){
    		global.ajaxLoading.pop("请选择一条数据操作！",true,1000);
    		return;
    	}	
    	$.ajax({
	    	type : 'post',
	    	async : false,
	    	url : appCtx + "system/vehicle/queryVehicleById.html?vehicleId="+checks[0],
	    	cache : false,
	    	dataType : "JSON",
	    	success : function(data) {			
	    		if(data){
	    			$("#updVehicle").modal("show");
	    			$("#updateVehicleId").val(checks[0]);
	    			$("#internal").val(data.internalNumber);
	    			$("#driverName").val(data.driverName);
	    			$("#phone").val(data.phone);
	    			$("#remark").val(data.remark);
	    		}  		
	    	}	
	    });	  
    	
    },
    updateVehicleInfo : function(){
    	var internal = $("#internal").val();
		var driverName = $("#driverName").val();
		var phone = $("#phone").val();
		var remark = $("#remark").val();
		var vehicleId = $("#updateVehicleId").val();
		$.ajax({
	    	type : 'post',
	    	async : false,
	    	url : appCtx + "system/vehicle/updateVehicleInfo.html",
	    	cache : false,
	    	dataType : "JSON",
	    	data : {"vehicleId":vehicleId,"internal":internal,"driverName":driverName,"phone":phone,"remark":remark},
	    	success : function(data) {			
	    		if(data){
	    			if(data.msg=="0"){
	    				global.ajaxLoading.pop("操作成功！",true,1000);
	    				vehicle.searchTable();
	    				$("#updVehicle").modal('hide');
	    			}else{
	    				global.ajaxLoading.pop("操作失败！",true,1000);
	    				$("#updVehicle").modal('hide'); 
	    			}
	    		}  		
	    	}	
	    });	  
    },
    exportVehicleInfo : function(){
    	var post = function(URL, PARAMS) {        
    	    var temp = document.createElement("form");        
    	    temp.action = URL;        
    	    temp.method = "post";        
    	    temp.style.display = "none";        
    	    for (var x in PARAMS) {        
    	        var opt = document.createElement("textarea");        
    	        opt.name = x;        
    	        opt.value = PARAMS[x];        
    	        temp.appendChild(opt);        
    	    }        
    	    document.body.appendChild(temp);        
    	    temp.submit();        
    	    return temp;        
    	};
    	var me = this;
		var answer = confirm("确定导出车辆信息?");
        if(!answer){
        	return false;
        }  
		var options = $("#vehicleTable").getOptions();
		var vehicleNo =$.trim($('#vehicleNo').val())
        var internalNumber = $.trim($('#internalNumber').val());
	    var paramsGrid = [{
            name : 'vehicleNo',
            value : vehicleNo
        },{
            name : 'internalNumber',
            value : internalNumber
        }];
	    $("#vehicleTable").flexOptions({
    		newp : 1,// 设置起始页
    		params : paramsGrid
    	});
		//获取导出的参数
		var exportParams = options.exportParams;
		post(appCtx + "system/vehicle/exportVehicles.html",{paramsGrid:exportParams});
    }
}

vehicle.init();
Date.prototype.toLocaleString = function() {
    return this.getFullYear() + "/" + (this.getMonth() + 1) + "/" + this.getDate() + "  " + this.getHours() + ":" + this.getMinutes() + ":" + this.getSeconds();
};